import Vue from 'vue'

// 深拷贝
function typeOf(obj) {
    const toString = Object.prototype.toString
    const map = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]': 'null',
        '[object Object]': 'object'
    }
    return map[toString.call(obj)]
}

export function deepCopy(data) {
    const t = typeOf(data)
    let o

    if (t === 'array') {
        o = []
    } else if (t === 'object') {
        o = {}
    } else {
        return data
    }

    if (t === 'array') {
        for (let i = 0; i < data.length; i++) {
            o.push(deepCopy(data[i]))
        }
    } else if (t === 'object') {
        for (let i in data) {
            o[i] = deepCopy(data[i])
        }
    }
    return o
}

// 生成随机字符串
export function randomStr(len = 32) {
    const $chars =
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    const maxPos = $chars.length
    let str = ''
    for (let i = 0; i < len; i++) {
        str += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return str
}

// 监听返回键
export function closeApp() {
    let exitFlag = false;
    window.api.addEventListener({
        name: 'keyback'
    }, function() {
        if (!exitFlag) {
            window.api.toast({
                msg: '再按一次退出应用',
                duration: 2000,
                location: 'bottom'
            });
            exitFlag = true;
        } else {
            window.api.closeWidget({
                silent: true
            });
        }
        setTimeout(function() {
            exitFlag = false;
        }, 2000);
    });
}

// 打开新窗口
export function openWin(name, pageParam) {
    window.api.closeToWin({ name: 'root' })
    window.api.openWin({
        name: name,
        url: `./` + name + `.html`,
        bgColor: "#fff",
        allowEdit: true,
        slidBackEnabled: false,
        pageParam: pageParam,
        reload: true
    });
}

//  返会上一页
export function comeBack() {
    window.api.closeWin({
        animation: {
            type: "reveal",
            subType: "from_left",
            duration: 300
        }
    });
}

// 关闭窗口
// export function closeWin(name) {
//     window.api.closeWin({
//         name: name,
//         url: `./` + name + `.html`,
//         bgColor: "#fff",
//         allowEdit: true
//     });
// }

/* 正整数 */
Vue.prototype.$getInteger = str => {
    let pattern = /^[1-9]\d*$/
    return pattern.test(str)
}

// 判断是否为链接
Vue.prototype.$validURL = str => {
    var pattern = new RegExp(
        "^(https?:\\/\\/)?" + // protocol
        "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
        "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
        "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
        "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
        "(\\#[-a-z\\d_]*)?$",
        "i"
    ); // fragment locator
    return !!pattern.test(str);
}

export function getFloat(num, n) {
    n = n ? parseInt(n) : 0;
    if (n <= 0) {
        return Math.round(num);
    }
    num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
    num = Number(num).toFixed(n); //补足位数
    return num;
}

Vue.prototype.$isJSON = str => {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            console.log(obj)
            if (typeof obj == 'object' && obj) {
                return false;
            } else {
                return false;
            }

        } catch (e) {
            console.log('error: ' + str + '!!!' + e);
            try {
                eval("(" + str + ")");
                return true;
            } catch (e) {
                return false;
            }
        }
    }
}